home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / _strptime.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  15KB  |  413 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Strptime-related classes and functions.
  5.  
  6. CLASSES:
  7.     LocaleTime -- Discovers and stores locale-specific time information
  8.     TimeRE -- Creates regexes for pattern matching a string of text containing
  9.                 time information
  10.  
  11. FUNCTIONS:
  12.     _getlang -- Figure out what language is being used for the locale
  13.     strptime -- Calculates the time struct represented by the passed-in string
  14.  
  15. '''
  16. import time
  17. import locale
  18. import calendar
  19. from re import compile as re_compile
  20. from re import IGNORECASE
  21. from re import escape as re_escape
  22. from datetime import date as datetime_date
  23.  
  24. try:
  25.     from thread import allocate_lock as _thread_allocate_lock
  26. except:
  27.     from dummy_thread import allocate_lock as _thread_allocate_lock
  28.  
  29. __all__ = []
  30.  
  31. def _getlang():
  32.     return locale.getlocale(locale.LC_TIME)
  33.  
  34.  
  35. class LocaleTime(object):
  36.     '''Stores and handles locale-specific information related to time.
  37.  
  38.     ATTRIBUTES:
  39.         f_weekday -- full weekday names (7-item list)
  40.         a_weekday -- abbreviated weekday names (7-item list)
  41.         f_month -- full month names (13-item list; dummy value in [0], which
  42.                     is added by code)
  43.         a_month -- abbreviated month names (13-item list, dummy value in
  44.                     [0], which is added by code)
  45.         am_pm -- AM/PM representation (2-item list)
  46.         LC_date_time -- format string for date/time representation (string)
  47.         LC_date -- format string for date representation (string)
  48.         LC_time -- format string for time representation (string)
  49.         timezone -- daylight- and non-daylight-savings timezone representation
  50.                     (2-item list of sets)
  51.         lang -- Language used by instance (2-item tuple)
  52.     '''
  53.     
  54.     def __init__(self):
  55.         '''Set all attributes.
  56.  
  57.         Order of methods called matters for dependency reasons.
  58.  
  59.         The locale language is set at the offset and then checked again before
  60.         exiting.  This is to make sure that the attributes were not set with a
  61.         mix of information from more than one locale.  This would most likely
  62.         happen when using threads where one thread calls a locale-dependent
  63.         function while another thread changes the locale while the function in
  64.         the other thread is still running.  Proper coding would call for
  65.         locks to prevent changing the locale while locale-dependent code is
  66.         running.  The check here is done in case someone does not think about
  67.         doing this.
  68.  
  69.         Only other possible issue is if someone changed the timezone and did
  70.         not call tz.tzset .  That is an issue for the programmer, though,
  71.         since changing the timezone is worthless without that call.
  72.  
  73.         '''
  74.         self.lang = _getlang()
  75.         self._LocaleTime__calc_weekday()
  76.         self._LocaleTime__calc_month()
  77.         self._LocaleTime__calc_am_pm()
  78.         self._LocaleTime__calc_timezone()
  79.         self._LocaleTime__calc_date_time()
  80.         if _getlang() != self.lang:
  81.             raise ValueError('locale changed during initialization')
  82.         _getlang() != self.lang
  83.  
  84.     
  85.     def __pad(self, seq, front):
  86.         seq = list(seq)
  87.         if front:
  88.             seq.insert(0, '')
  89.         else:
  90.             seq.append('')
  91.         return seq
  92.  
  93.     
  94.     def __calc_weekday(self):
  95.         a_weekday = [ calendar.day_abbr[i].lower() for i in range(7) ]
  96.         f_weekday = [ calendar.day_name[i].lower() for i in range(7) ]
  97.         self.a_weekday = a_weekday
  98.         self.f_weekday = f_weekday
  99.  
  100.     
  101.     def __calc_month(self):
  102.         a_month = [ calendar.month_abbr[i].lower() for i in range(13) ]
  103.         f_month = [ calendar.month_name[i].lower() for i in range(13) ]
  104.         self.a_month = a_month
  105.         self.f_month = f_month
  106.  
  107.     
  108.     def __calc_am_pm(self):
  109.         am_pm = []
  110.         for hour in (1, 22):
  111.             time_tuple = time.struct_time((1999, 3, 17, hour, 44, 55, 2, 76, 0))
  112.             am_pm.append(time.strftime('%p', time_tuple).lower())
  113.         
  114.         self.am_pm = am_pm
  115.  
  116.     
  117.     def __calc_date_time(self):
  118.         time_tuple = time.struct_time((1999, 3, 17, 22, 44, 55, 2, 76, 0))
  119.         date_time = [
  120.             None,
  121.             None,
  122.             None]
  123.         date_time[0] = time.strftime('%c', time_tuple).lower()
  124.         date_time[1] = time.strftime('%x', time_tuple).lower()
  125.         date_time[2] = time.strftime('%X', time_tuple).lower()
  126.         replacement_pairs = [
  127.             ('%', '%%'),
  128.             (self.f_weekday[2], '%A'),
  129.             (self.f_month[3], '%B'),
  130.             (self.a_weekday[2], '%a'),
  131.             (self.a_month[3], '%b'),
  132.             (self.am_pm[1], '%p'),
  133.             ('1999', '%Y'),
  134.             ('99', '%y'),
  135.             ('22', '%H'),
  136.             ('44', '%M'),
  137.             ('55', '%S'),
  138.             ('76', '%j'),
  139.             ('17', '%d'),
  140.             ('03', '%m'),
  141.             ('3', '%m'),
  142.             ('2', '%w'),
  143.             ('10', '%I')]
  144.         []([ (tz, '%Z') for tz_values in self.timezone for tz in tz_values ])
  145.         for offset, directive in ((0, '%c'), (1, '%x'), (2, '%X')):
  146.             current_format = date_time[offset]
  147.             for old, new in replacement_pairs:
  148.                 if old:
  149.                     current_format = current_format.replace(old, new)
  150.                     continue
  151.                 []
  152.             
  153.             time_tuple = time.struct_time((1999, 1, 3, 1, 1, 1, 6, 3, 0))
  154.             if '00' in time.strftime(directive, time_tuple):
  155.                 U_W = '%W'
  156.             else:
  157.                 U_W = '%U'
  158.             date_time[offset] = current_format.replace('11', U_W)
  159.         
  160.         self.LC_date_time = date_time[0]
  161.         self.LC_date = date_time[1]
  162.         self.LC_time = date_time[2]
  163.  
  164.     
  165.     def __calc_timezone(self):
  166.         
  167.         try:
  168.             time.tzset()
  169.         except AttributeError:
  170.             pass
  171.  
  172.         no_saving = frozenset([
  173.             'utc',
  174.             'gmt',
  175.             time.tzname[0].lower()])
  176.         if time.daylight:
  177.             has_saving = frozenset([
  178.                 time.tzname[1].lower()])
  179.         else:
  180.             has_saving = frozenset()
  181.         self.timezone = (no_saving, has_saving)
  182.  
  183.  
  184.  
  185. class TimeRE(dict):
  186.     '''Handle conversion from format directives to regexes.'''
  187.     
  188.     def __init__(self, locale_time = None):
  189.         '''Create keys/values.
  190.  
  191.         Order of execution is important for dependency reasons.
  192.  
  193.         '''
  194.         if locale_time:
  195.             self.locale_time = locale_time
  196.         else:
  197.             self.locale_time = LocaleTime()
  198.         base = super(TimeRE, self)
  199.         base.__init__({
  200.             'd': '(?P<d>3[0-1]|[1-2]\\d|0[1-9]|[1-9]| [1-9])',
  201.             'f': '(?P<f>[0-9]{1,6})',
  202.             'H': '(?P<H>2[0-3]|[0-1]\\d|\\d)',
  203.             'I': '(?P<I>1[0-2]|0[1-9]|[1-9])',
  204.             'j': '(?P<j>36[0-6]|3[0-5]\\d|[1-2]\\d\\d|0[1-9]\\d|00[1-9]|[1-9]\\d|0[1-9]|[1-9])',
  205.             'm': '(?P<m>1[0-2]|0[1-9]|[1-9])',
  206.             'M': '(?P<M>[0-5]\\d|\\d)',
  207.             'S': '(?P<S>6[0-1]|[0-5]\\d|\\d)',
  208.             'U': '(?P<U>5[0-3]|[0-4]\\d|\\d)',
  209.             'w': '(?P<w>[0-6])',
  210.             'y': '(?P<y>\\d\\d)',
  211.             'Y': '(?P<Y>\\d\\d\\d\\d)',
  212.             'A': self._TimeRE__seqToRE(self.locale_time.f_weekday, 'A'),
  213.             'a': self._TimeRE__seqToRE(self.locale_time.a_weekday, 'a'),
  214.             'B': self._TimeRE__seqToRE(self.locale_time.f_month[1:], 'B'),
  215.             'b': self._TimeRE__seqToRE(self.locale_time.a_month[1:], 'b'),
  216.             'p': self._TimeRE__seqToRE(self.locale_time.am_pm, 'p'),
  217.             'Z': self._TimeRE__seqToRE((lambda .0: for tz_names in .0:
  218. for tz in tz_names:
  219. tz)(self.locale_time.timezone), 'Z'),
  220.             '%': '%' })
  221.         base.__setitem__('W', base.__getitem__('U').replace('U', 'W'))
  222.         base.__setitem__('c', self.pattern(self.locale_time.LC_date_time))
  223.         base.__setitem__('x', self.pattern(self.locale_time.LC_date))
  224.         base.__setitem__('X', self.pattern(self.locale_time.LC_time))
  225.  
  226.     
  227.     def __seqToRE(self, to_convert, directive):
  228.         """Convert a list to a regex string for matching a directive.
  229.  
  230.         Want possible matching values to be from longest to shortest.  This
  231.         prevents the possibility of a match occuring for a value that also
  232.         a substring of a larger value that should have matched (e.g., 'abc'
  233.         matching when 'abcdef' should have been the match).
  234.  
  235.         """
  236.         to_convert = sorted(to_convert, key = len, reverse = True)
  237.         for value in to_convert:
  238.             if value != '':
  239.                 break
  240.                 continue
  241.         else:
  242.             return ''
  243.         regex = None.join((lambda .0: for stuff in .0:
  244. re_escape(stuff))(to_convert))
  245.         regex = '(?P<%s>%s' % (directive, regex)
  246.         return '%s)' % regex
  247.  
  248.     
  249.     def pattern(self, format):
  250.         '''Return regex pattern for the format string.
  251.  
  252.         Need to make sure that any characters that might be interpreted as
  253.         regex syntax are escaped.
  254.  
  255.         '''
  256.         processed_format = ''
  257.         regex_chars = re_compile('([\\\\.^$*+?\\(\\){}\\[\\]|])')
  258.         format = regex_chars.sub('\\\\\\1', format)
  259.         whitespace_replacement = re_compile('\\s+')
  260.         format = whitespace_replacement.sub('\\s+', format)
  261.         while '%' in format:
  262.             directive_index = format.index('%') + 1
  263.             processed_format = '%s%s%s' % (processed_format, format[:directive_index - 1], self[format[directive_index]])
  264.             format = format[directive_index + 1:]
  265.         return '%s%s' % (processed_format, format)
  266.  
  267.     
  268.     def compile(self, format):
  269.         '''Return a compiled re object for the format string.'''
  270.         return re_compile(self.pattern(format), IGNORECASE)
  271.  
  272.  
  273. _cache_lock = _thread_allocate_lock()
  274. _TimeRE_cache = TimeRE()
  275. _CACHE_MAX_SIZE = 5
  276. _regex_cache = { }
  277.  
  278. def _calc_julian_from_U_or_W(year, week_of_year, day_of_week, week_starts_Mon):
  279.     '''Calculate the Julian day based on the year, week of the year, and day of
  280.     the week, with week_start_day representing whether the week of the year
  281.     assumes the week starts on Sunday or Monday (6 or 0).'''
  282.     first_weekday = datetime_date(year, 1, 1).weekday()
  283.     if not week_starts_Mon:
  284.         first_weekday = (first_weekday + 1) % 7
  285.         day_of_week = (day_of_week + 1) % 7
  286.     
  287.     week_0_length = (7 - first_weekday) % 7
  288.     if week_of_year == 0:
  289.         return 1 + day_of_week - first_weekday
  290.     days_to_week = week_0_length + 7 * (week_of_year - 1)
  291.     return 1 + days_to_week + day_of_week
  292.  
  293.  
  294. def _strptime(data_string, format = '%a %b %d %H:%M:%S %Y'):
  295.     '''Return a time struct based on the input string and the format string.'''
  296.     global _TimeRE_cache
  297.     _cache_lock.__enter__()
  298.     
  299.     try:
  300.         if len(_regex_cache) > _CACHE_MAX_SIZE:
  301.             _regex_cache.clear()
  302.         
  303.         locale_time = _TimeRE_cache.locale_time
  304.         format_regex = _regex_cache.get(format)
  305.         if not format_regex:
  306.             
  307.             try:
  308.                 format_regex = _TimeRE_cache.compile(format)
  309.             except KeyError:
  310.                 err = None
  311.                 bad_directive = err.args[0]
  312.                 if bad_directive == '\\':
  313.                     bad_directive = '%'
  314.                 
  315.                 del err
  316.                 raise ValueError("'%s' is a bad directive in format '%s'" % (bad_directive, format))
  317.             except IndexError:
  318.                 raise ValueError("stray %% in format '%s'" % format)
  319.  
  320.             _regex_cache[format] = format_regex
  321.     finally:
  322.         pass
  323.  
  324.     found = format_regex.match(data_string)
  325.     if not found:
  326.         raise ValueError('time data %r does not match format %r' % (data_string, format))
  327.     found
  328.     if len(data_string) != found.end():
  329.         raise ValueError('unconverted data remains: %s' % data_string[found.end():])
  330.     len(data_string) != found.end()
  331.     year = 1900
  332.     tz = -1
  333.     week_of_year = -1
  334.     week_of_year_start = -1
  335.     found_dict = found.groupdict()
  336.     for group_key in found_dict.iterkeys():
  337.         if group_key == 'y':
  338.             year = int(found_dict['y'])
  339.             if year <= 68:
  340.                 year += 2000
  341.             else:
  342.                 year += 1900
  343.         year <= 68
  344.         if group_key == 'Y':
  345.             year = int(found_dict['Y'])
  346.             continue
  347.         weekday = julian = -1
  348.         if group_key == 'm':
  349.             month = int(found_dict['m'])
  350.             continue
  351.         hour = minute = second = fraction = 0
  352.         if group_key == 'B':
  353.             month = locale_time.f_month.index(found_dict['B'].lower())
  354.             continue
  355.         month = day = 1
  356.         if group_key == 'b':
  357.             month = locale_time.a_month.index(found_dict['b'].lower())
  358.             continue
  359.         _cache_lock.__exit__
  360.         if group_key == 'd':
  361.             day = int(found_dict['d'])
  362.             continue
  363.         _cache_lock
  364.         None if group_key == 'H' else ampm in ('', locale_time.am_pm[0])
  365.         if group_key == 'M':
  366.             minute = int(found_dict['M'])
  367.             continue
  368.         if group_key == 'S':
  369.             second = int(found_dict['S'])
  370.             continue
  371.         if group_key == 'f':
  372.             s = found_dict['f']
  373.             s += '0' * (6 - len(s))
  374.             fraction = int(s)
  375.             continue
  376.         if group_key == 'A':
  377.             weekday = locale_time.f_weekday.index(found_dict['A'].lower())
  378.             continue
  379.         None if group_key == 'a' else weekday == 0
  380.         None if group_key == 'j' else group_key == 'U'
  381.         if group_key == 'Z':
  382.             found_zone = found_dict['Z'].lower()
  383.             for value, tz_values in enumerate(locale_time.timezone):
  384.                 if found_zone in tz_values:
  385.                     if time.tzname[0] == time.tzname[1] and time.daylight and found_zone not in ('utc', 'gmt'):
  386.                         break
  387.                     else:
  388.                         tz = value
  389.                         break
  390.                 found_zone not in ('utc', 'gmt')
  391.             
  392.     
  393.     if julian == -1 and week_of_year != -1 and weekday != -1:
  394.         week_starts_Mon = None if week_of_year_start == 0 else False
  395.         julian = _calc_julian_from_U_or_W(year, week_of_year, weekday, week_starts_Mon)
  396.     
  397.     if julian == -1:
  398.         julian = (datetime_date(year, month, day).toordinal() - datetime_date(year, 1, 1).toordinal()) + 1
  399.     else:
  400.         datetime_result = datetime_date.fromordinal((julian - 1) + datetime_date(year, 1, 1).toordinal())
  401.         year = datetime_result.year
  402.         month = datetime_result.month
  403.         day = datetime_result.day
  404.     if weekday == -1:
  405.         weekday = datetime_date(year, month, day).weekday()
  406.     
  407.     return (time.struct_time((year, month, day, hour, minute, second, weekday, julian, tz)), fraction)
  408.  
  409.  
  410. def _strptime_time(data_string, format = '%a %b %d %H:%M:%S %Y'):
  411.     return _strptime(data_string, format)[0]
  412.  
  413.